const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const sequelize = require('./config/database');
const authRoutes = require('./routes/auth');
const scamRoutes = require('./routes/scams');
const commentRoutes = require('./routes/comments');
const adminRoutes = require('./routes/admin');
const uploadRoutes = require('./routes/upload');
const { errorHandler } = require('./middleware/error');

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 路由
app.use('/api/auth', authRoutes);
app.use('/api/scams', scamRoutes);
app.use('/api/comments', commentRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/upload', uploadRoutes);

// 错误处理
app.use(errorHandler);

// 数据库连接
sequelize.authenticate()
  .then(() => {
    console.log('数据库连接成功');
    return sequelize.sync({ alter: process.env.NODE_ENV === 'development' });
  })
  .then(() => {
    console.log('数据库同步完成');
  })
  .catch(err => {
    console.error('数据库连接失败:', err);
  });

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 